#include "htil.hpp"
#include "parse.cc"
#include "index.cc"
#include "./httplib/httplib.h"


// global define
// 项目运行在 8099端口
#define PORT 8099
const std::string input_path = "./data/input";
const std::string ouput_path = "./data/output/tmp.txt";
const std::string base_url = "https://www.boost.org";
const std::string dict_path = "./dict/jieba.dict.utf8";
const std::string hmm_model_path = "./dict/hmm_model.utf8";
const std::string user_dict_path = "./dict/user.dict.utf8";
const std::string idf_dict_path = "./dict/idf.utf8";
const std::string stop_word_path = "./dict/stop_words.utf8";
const std::string log_file = "./Log";

class Server
{
private:    
    Logging* log_point;
    Search search;
    Parse parse;
public:
    Server()
    {
        log_point = new Logging(log_file);
    }
    ~Server()
    {
        if(log_point != nullptr)
            delete log_point;
    }
    void init()
    {
        parse.init(log_point, input_path, ouput_path, base_url);
        if(!search.init(dict_path, hmm_model_path, user_dict_path, idf_dict_path, stop_word_path, log_point, ouput_path))
        {
            std::cout << "[ERROR] search init 失败 " << common::GetTime() << std::endl;
            log_point->WriteLogToDoc("ERROR", "search init 失败", common::GetTime());
            exit(3);
        }
        std::cout << "[SUCCESS] search init 成功 " << common::GetTime() << std::endl;
        log_point->WriteLogToDoc("SUCEESS", "search init 成功", common::GetTime());
        
    }
    void ServerSearch(const httplib::Request& req, httplib::Response& res)
    {
        res.set_header("Content-Type","application/json");//组织相应http头信息
        if (req.has_param("key")) 
        {
            std::string key = req.get_param_value("key");
            std::string tmp = search.SearchForDoc(key);
            std::cout << "[DEBUG] 请求: " << key << " " << common::GetTime() << std::endl;
            log_point->WriteLogToDoc("DEBUG", "请求: " + key, common::GetTime());
            res.body = tmp;
            res.status = 200;
        }
        else
        {
            std::cout << "[DEBUG] 空请求或无效请求 " << common::GetTime() << std::endl;
            log_point->WriteLogToDoc("DEBUG", "空请求或无效请求 ", common::GetTime());
            res.body = "";
            res.status = 400;
        }
    }

};


int main()
{
    Server server;
    server.init();
    httplib::Server svr;
    svr.Post("/api/boost/search", [&server](const httplib::Request& req, httplib::Response& res){
        server.ServerSearch(req, res);
    });
    svr.listen("0.0.0.0", PORT);
    return 0;
}
